#include <QTime>
#include <QTimer>
#include <QDateTime>
#include "agenttaskdatetimetrigger.h"
#include "Agent/agentprotocol.h"
#include "macro.h"

AgentTaskDateTimeTrigger::AgentTaskDateTimeTrigger(QMap <QByteArray,QByteArray> mapIPPortReqPacket,
       QByteArray packet,QString paramAppIP, quint16 paramAppPort, QObject *parent)
        :AgentTaskBase(mapIPPortReqPacket,packet,paramAppIP,paramAppPort,parent)
{
}

void AgentTaskDateTimeTrigger::slotInitDerivedClass()
{
    if(fieldTriggerTime.isEmpty())
    {
        emit sigSendDataToApp(agentProtocol->replyLineBadRequest()+"\n\n"
            "Field of Trigger-Time is missing!",appIP,appPort);
        deleteLater();
        return;
    }
    timer=new QTimer(this);

    QTime triggerTime=QTime::fromString(fieldTriggerTime,"hhmm");
    if(!triggerTime.isValid())
    {
        emit sigSendDataToApp(agentProtocol->replyLineBadRequest()+"\n\n"
            "Field of Trigger-Time is invalid!",appIP,appPort);
        deleteLater();
        return;
    }
    qint64 milliSecs;

    if(fieldTriggerDate.isEmpty()) //没有指定日期
    {
        milliSecs=QTime::currentTime().msecsTo(triggerTime);
        if(milliSecs<0)
            milliSecs=milliSecs+86400000; //第二天这个时间
        if(milliSecs<0) //如果仍然小于0，则删除任务。不可能会出现这个情况
        {
            deleteLater();
            return;
        }
    }
    else //指定了日期
    {
        QDateTime triggerDateTime=QDateTime::fromString(fieldTriggerDate+fieldTriggerTime,"yyyyMMddhhmm");
        if(!triggerDateTime.isValid())
        {
            emit sigSendDataToApp(agentProtocol->replyLineBadRequest()+"\n\n"
                "Field of Trigger-Time or Trigger-Date is invalid!",appIP,appPort);
            deleteLater();
            return;
        }
        milliSecs=QDateTime::currentDateTime().msecsTo(triggerDateTime);

        if(milliSecs<0)
        {
            deleteLater();
            return;
        }
    }


    QTimer::singleShot(milliSecs,this,SLOT(slotTimerSendPacketToServer()));
    isCreatedSuccessfully=true;

}

void AgentTaskDateTimeTrigger::analyzeIncomeDatagram(QByteArray packet)
{
    QByteArray packetUpper=packet.simplified().toUpper();

    if(packetUpper.startsWith("ERR"))
    {
        emit sigSendDataToApp(agentProtocol->replyLineBadRequest()+"\n\n"+
            packet,appIP,appPort);
        deleteLater();
        return;
    }
    emit sigSendDataToApp(packet,appIP,appPort);
}

void AgentTaskDateTimeTrigger::slotTimerSendPacketToServer()
{
    emit sigSetIPAnalyzeIncomeDatagram(fieldPayLoad,QHostAddress(appIP),appPort);
    //slotSendPacket(fieldPayLoad,aServerIP,aServerPort);
    if(!fieldTriggerDate.isEmpty()) //只执行一次
    {
        QTimer::singleShot(5000,this,SLOT(deleteLater()));
        return;
    }
    else //每天执行
    {
        QTimer::singleShot(86400000,this,SLOT(slotTimerSendPacketToServer()));
    }
}

AgentTaskDateTimeTrigger::~AgentTaskDateTimeTrigger()
{

}
